import { PositionHelper } from "utils/position/PositionHelper";
import { EntityDB } from "../../../EntityManager/EntityDB";
import { PollingStationManager } from "../../../PollingStation/PollingStationManager";
import { StationNetwork } from "GameLoop/Path/StationNetwork";
import { PowerCreepArgHelper } from "utils/helper/Z_PowerCreepArgHelper";
import { UtilsHelper } from "utils/position/UtilsHelper";
import { MinerialEntity } from "../../../EntityManager/Entitys";

  interface WorldGetter
{
    EntityDB:EntityDB
    Station:PollingStationManager
    registerNotify(region:EventRegion,eventtype:INotifyEvent):void
}

/**
 * 事件检测
 */
export class EventChecker
{
      private static addNewRoom(lord:Room,room:Room,route:ICacheResult<IRouteCache>,emitter:TEventEmitter<TEventTypes> ) 
    {
        if(Game.shard.name == "shard3")
        {
            // shard3 放弃自动开外矿
            lord.log(`warn`,Game.shard.name,room.name,`放弃开外矿`);
            return false
        }
        if(lord.getType() ==1 && route  )
        {   
            if(room.controller && route.value.route.length<=3)
            {
                if(( !room.controller.reservation && room.controller.level==0)|| room.isMyResverse())
                {
                    // 普通外矿
                    lord.log(`warn`,Game.shard.name,room.name,`普通外矿房`);
                    emitter(Game.shard.name,"AddMineRoom",{
                        region: lord.name,
                        room:room.name,
                        type:3,
                    })
                    
                    return true
                }
            }
            else if(   UtilsHelper.isCenterRoom(room.name) )
            {
                const ret = UtilsHelper.isCenterRoom(room.name);
                if(ret == 1)
                {
                    if(route.value.route.length<=2)
                    {
                        lord.log(`warn`,Game.shard.name,room.name,`中央房外矿房`);
                        // 中心9房
                        emitter(Game.shard.name,"AddMineRoom",{
                            region: lord.name,
                            room:room.name,
                            type:6,
                        })
                    }
                }
                else  if(ret == 2) 
                {
                    if(route.value.route.length<=3)
                    {
                        lord.log(`warn`,Game.shard.name,room.name,`中央房外矿房`);
                        // 中心9房
                        emitter(Game.shard.name,"AddMineRoom",{
                            region: lord.name,
                            room:room.name,
                            type:6,
                        })
                    }
                }
                

                return true
            }
            else if(  UtilsHelper.IsHillway(room.name)&& route.value.route.length<=7)
            {
                // 过道房
                global.Log.Info(`更新过道房房间 : ${room.name}`);
                emitter(Game.shard.name,"AddHallwayRoom",{
                    region: lord.name,
                    room:room.name,
                    type:5,
                })
            }
            else 
            {
                
            }
        }
        else 
        {
            // lord.log(`warn`,`${lord.name}->[${lord.getType()}]`,room.name,`路由错误开外矿失败`,JSON.stringify(route));
        }
        
        return false;
    }
    private static findLordRoom(room:Room,range:number,ingrouRoom?:string) 
    {
        let roomCache:{room:string,distance:ICacheResult<IRouteCache>}=undefined as any;
        if(room.memory.lst&& Game.time-room.memory.lst<10000)
        {
            // 同一个房间扫描间隔过短，至少10000tick之后再判断是否归属与哪一个主房
            return undefined;
        }
        room.memory.lst = Game.time;
        for(let k of global.resourceStats.myrooms)
        {
            
            const mainroom=Game.rooms[k];
            if(mainroom.getType()!== 1)
            {
                    
                continue;
            }
            if(k == room.name)
            {
                room.log(`warn`, room.name,`添加失败 同一个房间`);
                continue;
            }
            if(ingrouRoom && ingrouRoom == k)
            {
                continue;
            }
            if(Game.map.getRoomLinearDistance(mainroom.name,room.name)>range)
            {
                // mainroom.log(`warn`, mainroom.name,`添加失败 房间距离大于5`);
                continue;
            }
            if( UtilsHelper.IsHillway(room.name) && Game.map.getRoomLinearDistance(PositionHelper.getCenterRoom(mainroom.name),PositionHelper.getCenterRoom(mainroom.name))<=2)
            {
                // 房间靠近中心房
                continue;
            }
            const route = StationNetwork.getInstance.findRoute(mainroom.name,room.name,1.5);
            if(route)
            {
                if(route.value.route.length ==2)
                {
                    roomCache={room:mainroom.name,distance:route};
                    return roomCache
                }
                else 
                {
                    if(!roomCache || roomCache.distance.value.route.length>route.value.route.length)
                    {
                        if(UtilsHelper.isCenterRoom(room.name))
                        {
                            // 终点是中心房
                            roomCache={room:mainroom.name,distance:route};
                        }
                        else 
                        {
                            // 终点不是中心房
                            if(route.value.route.some(e=>UtilsHelper.isCenterRoom(e))  )
                            {
                                // 路径中存在中央房
                                
                            }
                            else 
                            {
                                // 路径中不存在中央房
                                roomCache={room:mainroom.name,distance:route};
                            }
                        }
                    }
                }
                
            }
            else 
            {
                mainroom.log(`warn`, room.name,`添加失败找不到路由`);
            }
        }
        return roomCache
    }
    /**
     * 当房间没有被写入 config信息时初始化房间
     * @param worldgetter 
     * @param room 
     * @param emitter 
     * @returns 
     */
    public static  checkInitRoom(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
         
        if( Object.keys(Game.rooms).length==1 || (Object.values(Game.rooms).findIndex(e=>e.getType() ==1)  ==-1))
        {
            global.Log.Info(`checkInitRoom 1`);
            // 第一个房
            // 进行初始化
            global.Log.Debug(` -checkInitRoom`, `${room.name} `);
            if(room.controller.my)
            {
                emitter(Game.shard.name,"AddRoomEvent",{
                    region:room.name,
                    room:room.name,
                    type:1,
                })
            }
           
        }
        else
        {
            if(room.controller?.my)
            {
                emitter(Game.shard.name,"AddRoomEvent",{
                    region:room.name,
                    room:room.name,
                    type:1,
                })
                room.log(`warn`,Game.shard.name,room.name,`新增主房`);
                return ;
            }
            if(Game.flags[`${room.name}_ban`])
            {
                // 此房间已经被禁用了
                return ;
            }
            // global.Log.Info(`checkInitRoom 2`);
            if(room.memory.lord)
            {
                // 已经更新过主房了
                const mainroom=Game.rooms[room.memory.lord];
                if(mainroom)
                {
                    const route = StationNetwork.getInstance.findRoute(mainroom.name,room.name);
                    if(route)
                    {
                        if(EventChecker.addNewRoom(mainroom   ,room,route,emitter))
                        {

                        }
                        else 
                        {
                            // mainroom.log("warn",`添加外矿房失败`,`${room.name}`,`${JSON.stringify(route.value)}`)
                        }
                    }
                    else
                    {
                        mainroom.log(`warn`, room.name,`添加失败找不到路由`);
                    }
                }
            }
            else
            {
                let roomCache= EventChecker.findLordRoom(room,7);
                // room.log(`warn`,'添加新房');
                if(roomCache)
                {
                    
                    if(EventChecker.addNewRoom(Game.rooms[roomCache.room]   ,room,roomCache.distance,emitter))
                    {

                    }
                    else 
                    {
                        // Game.rooms[roomCache.room].log("warn",`添加外矿房失败`,`${room.name}`,`${JSON.stringify(roomCache.distance.value)}`)
                    }
                }
                else 
                {
                    // global.Log.Error(`[${room.name}]无法找到此房间的主房间`)
                }
            }
 
        }
    }

    // 检测更新房间
    public static  checkNewRoom(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
      
        if(!worldgetter.EntityDB.getEntity("SpawnEntity",room.name))
        {
            global.Log.Debug(` -checkNewRoom`, `${room.name} `);
            // 房间实体未初始化
          
            emitter(Game.shard.name,"AddRoomEvent",{
                region:room.memory.lord,
                room:room.name,
                type:room.getType(),
            })
        }
    }
    public static  checkTransferOutMine(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
        if(room.getType() ==3 && room.canExecute(100))
        {
            if(room.memory.state == 1 )
            {
                // 房间未启用
                const route = StationNetwork.getInstance.findRoute(room.name,room.memory.lord);
                if(route && route.value.route.length>1)
                {
                    const result = EventChecker.findLordRoom(room,3,room.memory.lord);
                    if(result)
                    {
                        if(result.distance.value.route.length==2)
                        {
                            // 新的lord房间距离为1
                            
                            const oldLordRoom = room.lordRoom();
                            oldLordRoom.deleteRemoteMine(room.name)
                            const newlordRoom = Game.rooms[result.room];
                            // 清除mine 房间的内存
                            room.memory.lord = result.room;
                            // 添加到新房间
                            EventChecker.addNewRoom(newlordRoom,room,result.distance,emitter);
                        }
                    }
                }
            }
            else 
            {

            }
            
        }
    }

      /**
     * 外矿防守事件
     * @param worldgetter 
     * @param room 
     * @param emitter 
     */
    public static  checkRemoveMine(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
        if(room.getType() ==3 && room.controller.my)
        {
            (global.test as any).removeRemoteMine(room.lordRoom().name,room.name);
        }
    }
    public static  initRoomAttribute(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
      
        room.initAttributes();
        room.controller.initAttributes();
    }
    /**
     * 检测我的房间被丢弃
     * @param worldgetter 
     * @param room 
     * @param emitter 
     */
    public static  checkMyRoomLose(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
        if(room.memory?.config?.type == 1 && !room.controller.my)
        {
            // 初始化过房间，但是不是我的了
            room.log("warn",'检测到房间丢失')
            emitter(Game.shard.name,"LostRoomEvent",{
                region:Game.shard.name,
                room:room.name,
                type:room.getType(),
            })
        }
        
    }
   
    public static  checkLevelUp(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
        if(room.memory.history && room.memory.history.level< room.controller.level)
        {
            
            // 房间实体未初始化
            emitter(room.name,"LevelUp",{
                region:room.memory.lord,
                room:room.name,
                type:room.getType(),
            })
            // 升级事件延长1t。用于build检测site。因为放置site之后下一帧才会有site
            worldgetter.registerNotify(room.name,{
                type:"LevelUp",
                region:room.memory.lord,
                room:room.name
            })
            room.memory.history.level = room.controller.level;
        }
    }

    public static  checkRepair(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
        if(!room.lordRoom())
        {
            room.log("warn",room.memory.lord,"此房间的主房间无法访问");
            delete Memory.rooms[room.name];
            return 
        }
        if(room.canExecute(50) && room.lordRoom())
        {
            // 房间实体未初始化
            emitter(room.name,"RepairEvent",{
                region:room.memory.lord,
                room:room.name,
                type:room.getType(),
            })

            
            // global.Log.Info(`${Game.time} 维修事件`);
        }
        if(room.canExecute(100) &&  room.getType() == 1)
        {
            // 房间实体未初始化
            emitter(room.name,"RepairRampartEvent",{
                region:room.memory.lord,
                room:room.name,
                type:room.getType(),
            })
            // global.Log.Info(`${Game.time} 维修事件`);
        }
    }


    public static  checkEnergyCapacityIncress(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
        if(room.memory.history && room.memory.history.energyCapacity< room.energyCapacityAvailable)
        {
            // 房间实体未初始化
            emitter(room.name,"EnengyCapacityUp",{
                region:room.memory.lord,
                room:room.name,
                type:room.getType(),
            })
        }
    }


    public static  checkFillAnyStore(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
        if(room.canExecute(5+room.controller.level*4))
        {
            if(room.energyCapacityAvailable> 1050 && room.energyAvailable != room.energyCapacityAvailable)
            {
                emitter(room.name,"FillAnyStore",{
                    region:room.memory.lord,
                    room:room.name,
                    type:room.getType(),
                    filltype:[STRUCTURE_LAB,STRUCTURE_TOWER,STRUCTURE_EXTENSION]
                })
            }
            else 
            {
                emitter(room.name,"FillAnyStore",{
                    region:room.memory.lord,
                    room:room.name,
                    type:room.getType(),
                    filltype:[STRUCTURE_LAB,STRUCTURE_TOWER]
                })
            }
            // 房间实体未初始化
           
            // global.Log.Info(`${Game.time} 维修事件`);
        }
    }


    /**
     * 房间防守事件
     * @param worldgetter 
     * @param room 
     * @param emitter 
     */
    public static  checkDefend(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
        if(room.canExecute(50))
        {
            const hostilecache  = worldgetter.Station.PollHostiles(room.name);
            if(hostilecache && hostilecache.cacheData.length>0)
            {
                emitter(room.name,"DefendEvent",{
                    region:room.memory.lord,
                    room:room.name,
                    type:room.getType(),
                })
                // return ;
            }
            else 
            {
               
            }

        }
        
           
        const eventcache = room.getWorld().PollEvents(room.name);
        if(eventcache && eventcache.cacheData.length)
        {
            // const structurecache = room.getWorld().PollStructure(room.name);
           
            // if( room.getType() == 1 &&structurecache && structurecache.checkStructureDestory(STRUCTURE_RAMPART))
            // {
            //     // 小概率 当 墙刚好破的时候 刷新了缓存。导致没有检测到
            //     const  CacheHostiles = room.getHostileCreeps();
            //     if(  CacheHostiles.length>0)
            //     {
            //         // rampart 破了而且还有敌人。开启安全模式
            //         room.activeSafeMode();
            //     }
            // }
             
            
            const beAttack = eventcache.isBeAttacked();
            if(beAttack)
            {
                emitter(room.name,"DefendEvent",{
                    region:room.memory.lord,
                    room:room.name,
                    type:room.getType(),
                })

                emitter(room.name,"RepairRampartEvent",{
                    region:room.memory.lord,
                    room:room.memory.lord,
                    type:room.getType(),
                })
                eventcache.getAttacker()
                const hostcreeps   = worldgetter.Station.PollHostiles(room.name);
                if(hostcreeps && hostcreeps.cacheData.length>0)
                {
                    if(hostcreeps.damage_sum>400 && hostcreeps.cacheData.length>=2)
                    {
                        // 暂停所有的外面的任务
                        let time = 3000;
                        if(room.canExecute(15))
                        {
                            
                            room.getTaskByType("creep",(e:ITaskDeclare["creep"])=>
                             
                                (e.data.room &&e.data.room !== room.name) || e.data.type == "harvestM").forEach(e=>room.pauseTask(e,time));
                            room.getTaskByType("team",(e:ITaskDeclare["team"])=>e.data.room !== room.name).forEach(e=>room.pauseTask(e,time));
                        }
                    }
                    
                }
            }
        }
    }
 
      /**
     * 外矿防守事件
     * @param worldgetter 
     * @param room 
     * @param emitter 
     */
       public static  checkDefendMine(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
       {
        // global.world.PollEvents("E53S16").inquireEvent(EVENT_RESERVE_CONTROLLER)
        if(room.canExecute(51))
        {
            if(room.getType() == 3)
            {
                const hostilecache  = worldgetter.Station.PollHostiles(room.name);
                if(hostilecache && hostilecache.cacheData.length>0)
                {
                    emitter(room.name,"DefendMineRoom",{
                        region:room.memory.lord,
                        room:room.name,
                        type:room.getType(),
                    })
                }
                else
                {
                    const eventsCache = worldgetter.Station.PollEvents(room.name);
                    if(eventsCache)
                    {
                        
                        const events = eventsCache.inquireEvent(EVENT_ATTACK_CONTROLLER);
                        if(events &&events.length>0 )
                        {
                            emitter(room.name,"DefendMineRoom",{
                                region:room.memory.lord,
                                room:room.name,
                                type:room.getType(),
                            })
                            return 
                        }else {
                            const events = eventsCache.inquireEvent(EVENT_RESERVE_CONTROLLER);
                            if(events &&events.length>0 && !room.isMyResverse())
                            {
                                global.Log.Debug(`${room.name}有人在预定我的控制器`,`抛出事件 ${JSON.stringify(events[0])}`)
                                // 不是我在预定
                                emitter(room.name,"DefendMineRoom",{
                                    region:room.memory.lord,
                                    room:room.name,
                                    type:room.getType(),
                                })
                                // 采集任务暂停

                                emitter(room.name,"PauseEvent",{
                                    region:room.memory.lord,
                                    room:room.name,
                                    type:room.getType(),
                                    pause:1500,
                                    creepTaskType:["harvest","claim","build"]
                                })
                            }
                        }
                        
                    }
                }
            }
            
            
        }
        
       }
     /**
     * 房间建设事件
     * @param worldgetter 
     * @param room 
     * @param emitter 
     */
    public static  checkBuild(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
         
        if(room.canExecute(111) )
        {
             
            const construcesitecache  = worldgetter.Station.PollConstructSites(room.name);
            if(construcesitecache && construcesitecache.cacheData.length>0)
            {
                
                emitter(room.name,"BuildEvent",{
                    region:room.memory.lord,
                    room:room.name,
                    type:room.getType(),
                })
            }
            else
            {
                
            }
            
        }
    }
    

    /**
     * 房间防守事件
     * @param worldgetter 
     * @param room 
     * @param emitter 
     */
    public static  checkReserve(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
    // 是外矿
   
        if(room.getType() ==3 && room.canExecute(50) &&    !room.memory.state)
        {
            if(room.lordRoom().controller.level>=3 && room.lordRoom().controller.level<=6)
            {
                if(!room.controller.reservation || room.controller.reservation.ticksToEnd<3000)
                { 
                    emitter(room.name,"ReserveEvent",{
                        region:room.memory.lord,
                        room:room.name,
                        type:room.getType(),
                    })
                }
            }
            else  if( room.lordRoom().controller.level>=7)
            {
                if(!room.controller.reservation || room.controller.reservation.ticksToEnd<1500)
                { 
                    emitter(room.name,"ReserveEvent",{
                        region:room.memory.lord,
                        room:room.name,
                        type:room.getType(),
                    })
                }
            }
            
        }
    }
      /**
     * 房间防守事件
     * @param worldgetter 
     * @param room 
     * @param emitter 
     */
    public static  checkMinerial(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
    // 是外矿
    
        if(room.getType() ==6 &&  room.canExecute(1013) && room.lordRoom().controller.level>=7 && !room.memory.state)
        {
            const minerials = room.getMinerial();
            if(minerials.length>0 && !room.getEntityByID<MinerialEntity>(minerials[0].id)?.getNodeMemory().state)
            {
                emitter(room.name,"Harvest",{
                    region:room.memory.lord,
                    room:room.name,
                    type:room.getType(),
                    source:minerials[0].id
                })
                room.log(`info`,'发布采集元素矿事件');
            }
             
        }
    }
    public static  checkHallwayHarvest(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
        
        if(!room.memory.et|| Game.time - room.memory.et>300)
        {
            EventChecker.checkDeposit(worldgetter,room,emitter);
            EventChecker.checkPowerBlank(worldgetter,room,emitter);
            room.memory.et = Game.time;
        }
    }
    /**
     * 检测商品采集
     * @param worldgetter 
     * @param room 
     * @param emitter 
     */
    private static  checkDeposit(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
    // 是外矿
    // 商品不能定时。检测因为不是一直都有视野的
        if(  room.lordRoom().controller.level>=8 && !room.memory.state)
        {
            // if(room.getStructures(STRUCTURE_WALL).length)
            // {
            //     return 
            // }
            const depos = room.getDeposit();
            if(depos.length>0 && !room.memory.state)
            {
                for(const e of depos)
                {
                    if(e.lastCooldown<100)
                    {
                        emitter(room.memory.lord,"HarvestDepo",{
                            region:room.memory.lord,
                            room:room.name,
                            type:room.getType(),
                            source:e.id
                        })
                    }
                }
                
                // room.log(`info`,'发布采集元素矿事件');
            }
        }
    }

    /**
     * 检测Power采集
     * @param worldgetter 
     * @param room 
     * @param emitter 
     */
    private static  checkPowerBlank(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
    // 是外矿
    // 商品不能定时。检测因为不是一直都有视野的
        if(  room.lordRoom().controller.level==8 && ! room.lordRoom().memory.state)
        {
            const pb = room.getStructures(STRUCTURE_POWER_BANK);
            // room.log(`warn`,'power 检测',)
            if(pb.length>0  )
            {
                for(const e of pb)
                {
                    if(e.ticksToDecay>2000&& e.power>1500)
                    {
                        emitter(room.memory.lord,"HarvestPower",{
                            region:room.memory.lord,
                            room:room.name,
                            type:room.getType(),
                            source:e.id
                        })
                    }
                }
                // room.log(`info`,'发布采集元素矿事件');
            }
        }
    }
    public static checkPauseRoomTask(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
        if(room.getType() == 6&& room.canExecute(1000))
        {
            // 检测9房是否暂停
             
            // 检测路径上是否有tower
            {
                const route = StationNetwork.getInstance.findRoute(room.name,room.lordRoom().name);
                if(route)
                {
                    route.value.route.forEach(e=>
                        {
                            if(Game.rooms[e])
                            {
                                const time = EventChecker.findPauseTime(Game.rooms[e]);
                                if(time)
                                {
                                    emitter(room.name,"PauseEvent",{
                                        region:room.memory.lord,
                                        room:room.name,
                                        type:room.getType(),
                                        pause:time
                                    })
                                    return 
                                }
                            }
                        })
                    
                }
            }
        }
    }

    public static checkTick(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
        emitter(room.name,"Tick",{
            region:room.memory.lord,
            room:room.name,
        })
        if(room.controller.level ==8)
        {
            if(room.canExecute(10001))
            {
                emitter(room.name,"Observe",{
                    region:room.memory.lord,
                    room:room.name,
                }) 
            }
            if(room.canExecute(371))
            {
                // 观察过道
                emitter(room.name,"Observe",{
                    region:room.memory.lord,
                    room:room.name,
                    OBType:1,
                })
            }
        }
        else 
        {
            if(room.canExecute(10001))
            {
                emitter(room.name,"Observe",{
                    region:room.memory.lord,
                    room:room.name,
                }) 
            }
        }
        
    }


    public static checkPowerTask(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
        const lordroom = room.lordRoom();
        if(lordroom.controller.level !== 8)
        {
            return 
        }
        const core = lordroom.getEntity("CoreEntity");
        if(!core)
        {
            return ;
        }
        if(lordroom.canExecute(30))
        {
            const mines = lordroom.getEntitys("InnerMineEntity");
            for(const e of mines)
            {
                const opevent = PowerCreepArgHelper.getOpRoomObjectEvent(e.getSource(),PWR_REGEN_SOURCE,lordroom.name,60);
                if(opevent)
                {
                    emitter(room.name,"PowerEvent",opevent)
                }
            }
        }
        if(core.resourceCount(RESOURCE_OPS)<1000)
        {
            return ;
        }
        if(lordroom.canExecute(100))
        {
            // lordroom.
            // 检测opminer
            

         
            if(core.Factory && !core.Factory?.level)
            {
                const opevent = PowerCreepArgHelper.getOpRoomObjectEvent(core.Factory,PWR_OPERATE_FACTORY,lordroom.name);
                if(opevent)
                {
                    emitter(room.name,"PowerEvent",opevent)
                }
            }


        }

        if(lordroom.canExecute(10))
        {
            // lordroom.log("info","op ext",lordroom.energyAvailable,lordroom.energyCapacityAvailable)
            if(lordroom.energyAvailable<lordroom.energyCapacityAvailable*0.6)
            {
                const obj =  core.getTakeStores({resourceType: RESOURCE_ENERGY,amount: 50000});
                if(obj.length>0)
                {
                    const opevent = PowerCreepArgHelper.getOpRoomObjectEvent(obj[0],PWR_OPERATE_EXTENSION,lordroom.name);
                    if(opevent)
                    {
                        emitter(room.name,"PowerEvent",opevent)
                    }
                }
            }
            if(core.Storage &&core.Storage.store.getFreeCapacity()<50000)
            {
                const opevent = PowerCreepArgHelper.getOpRoomObjectEvent(core.Storage,PWR_OPERATE_STORAGE,lordroom.name);
                if(opevent)
                {
                    emitter(room.name,"PowerEvent",opevent)
                }
            }
        }
        if(lordroom.canExecute(10))
        {
            const spawn = lordroom.getEntity("SpawnEntity");
            if(spawn.spawnQueue.size()>0)
            {
                const ids = spawn.spawnStructures();
                for(const e of ids)
                {
                    const p = e;
                    if( p.spawning)
                    {
                        const opevent = PowerCreepArgHelper.getOpRoomObjectEvent(p,PWR_OPERATE_SPAWN,lordroom.name);
                        if(opevent)
                        {
                            emitter(room.name,"PowerEvent",opevent);
                            break;
                        }
                    }
                }
            }
        }
    }
    public static checkBuildComplete(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
        const eventcache = room.getWorld().PollEvents(room.name);
        if(eventcache && eventcache.cacheData.length)
        {
            
            const events = eventcache.inquireEvent(EVENT_BUILD);
            if(events)
            {
                events.forEach(e=>
                    {
                        const gameobj = Game.getObjectById(e.data.targetId as any) as ConstructionSite;
                        if(!gameobj || gameobj.structureType ==STRUCTURE_RAMPART ||gameobj.structureType ==STRUCTURE_WALL || gameobj.progress == gameobj.progressTotal)
                        {
                            emitter(room.name,"BuildItemComplete",{
                                region:room.lordRoom().name,
                                room:room.name,
                                type:room.getType(),
                            })
                            if(gameobj)
                            {
                                room.log('info',`检测到建设完成`,gameobj.structureType,gameobj.progress,gameobj.progressTotal)
                            }
                            else 
                            {
                                room.log('info',`检测到建设完成`,  e.objectId)
                              
                            }
                            return ;
                        }
                    })
            }
        }
    }
    public static checkBeAttack(worldgetter:WorldGetter, room:Required<Room>,emitter:TEventEmitter<TEventTypes>)
    {
        
        const eventcache = room.getWorld().PollEvents(room.name);
        if(eventcache && eventcache.cacheData.length)
        {
           
            const events = eventcache.inquireEvent(EVENT_ATTACK);
            if(events)
            {
                const find = _.find(events,e=>

                Game.getObjectById(e.data.targetId as (Id<OwnedStructure|Creep>))?.my)  as MyEventItem<EVENT_ATTACK>
                if(find)
                {
                    const creep = Game.getObjectById(find.data.targetId as Id<Creep>);
                    if(!creep?.memory.taskid  )
                    {
                        return
                    }
                    const task = creep!.ownerRoom().findTaskById(creep!.memory.taskid) as ITaskDeclare["creep"];
                    if(!task || !task.data.room)
                    {
                        return ;
                    }
                    if(room.getType() ==6)
                    {
                        const time = EventChecker.findPauseTime(room);
                        if(time)
                        {
                            const route = StationNetwork.getInstance.findRoute(creep.ownerRoom().name,task.data.room);
                            if(route && route.value.route.includes(room.name ))
                            {
                                emitter(room.name,"PauseEvent",{
                                    region:creep.ownerRoom().name,
                                    room:task.data.room,
                                    type:room.getType(),
                                    pause:time
                                })
                            }
                            
                        }
                        else 
                        {
                            if(UtilsHelper.isCenterRoom(room.name) ==2)
                            {
                                emitter(room.name,"DefendMineRoom",{
                                    region:room.memory.lord,
                                    room:room.name,
                                    type:room.getType(),
                                })
                            }
                        }
                    }
                    else  if(room.getType() ==3)
                    {
                        if(creep.ownerRoom().controller!.level<4)
                        {
                            emitter(room.name,"PauseEvent",{
                                region:creep.ownerRoom().name,
                                room:task.data.room,
                                type:room.getType(),
                                creepTaskType:"harvest",
                                pause:1500
                            })
                        }
                    }
                }
            }

            const destoryram =eventcache.inquireStructureDestory(STRUCTURE_RAMPART);
            if(destoryram && destoryram.length>0 && room.getType() == 1 )
            {
                const  CacheHostiles = room.getHostileCreeps();
                if(  CacheHostiles .length>0)
                {
                    // rampart 破了而且还有敌人。开启安全模式
                    room.activeSafeMode();
                }
            }
        }
    }
    private static findPauseTime (room:Room) 
    {
        if(room.getType() ==6)
        {
            const towers = room.getStructures(STRUCTURE_TOWER);
            if(towers.length>0 && towers[0].effects)
            {
                const effect = towers[0].effects.find(e=>e.effect == EFFECT_COLLAPSE_TIMER);
                if(effect)
                {
                    return effect.ticksRemaining      
                }
            }
        }
        
        return 0 
    }
}